package com.bufbomb.datastore;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
	private final int filesize = 800 * 1024;
	private final int chunksize = 8 * 1024;
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		
		if(!userService.isUserAdmin())
		{
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
			return;
		}
		
		try {
			req.setCharacterEncoding("UTF-8");
			ServletFileUpload upload = new ServletFileUpload();
			String name = null;
        	Text description = null;
        	List<DataItem> dataItems = null;
        	FileItemIterator iterator = upload.getItemIterator(req);
		    
		    while (iterator.hasNext()) {
		    	FileItemStream itemStream = iterator.next();
		    	
		    	//TODO: Check the parameter
		        if (itemStream.isFormField()) {
		        	String fieldName = itemStream.getFieldName();
		        	if (fieldName.equals("name"))
		        	{
		        		InputStream stream = itemStream.openStream();
		        		name = Streams.asString(stream, "UTF-8");
		        		stream.close();
		        	}else if (fieldName.equals("description"))
		        	{
		        		InputStream stream = itemStream.openStream();
		        		description = new Text(Streams.asString(stream, "UTF-8"));
		        		stream.close();
		        	}
		        } 
		        else {
		        	String fieldName = itemStream.getFieldName();
		        	if(fieldName.equals("myfile"))
		        	{
		        		InputStream stream = itemStream.openStream();
			        	int len;
			        	int totalLength = 0;
			        	dataItems = new ArrayList<DataItem>();
			        	int index = 0;
			        	byte[] buffer = new byte[filesize];
			        	while ((len = stream.read(buffer, totalLength, chunksize)) != -1) {
			        		totalLength += len;
			        		if(totalLength > filesize - chunksize)
			        		{
			        			byte[] blobArray = new byte[totalLength];
					        	System.arraycopy(buffer, 0, blobArray, 0, totalLength);
					        	Blob blob = new Blob(blobArray);
			        			DataItem di = new DataItem(index, blob);
			        			dataItems.add(di);
			        			index ++;
			        			totalLength = 0;
			        		}
			        	}
			        	if(totalLength != 0)
			        	{
				        	byte[] blobArray = new byte[totalLength];
				        	System.arraycopy(buffer, 0, blobArray, 0, totalLength);
				        	Blob blob = new Blob(blobArray);
		        			DataItem di = new DataItem(index, blob);
		        			dataItems.add(di);
		        			index ++;
			        	}
		        	}
		        }
		    }
		    
		    if (name != null && description != null && dataItems.size() > 0)
		    {
		    	FlashItem si = new FlashItem(name, description);
		    	si.setDataItems(dataItems);
	        	PersistenceManager pm = PMF.get().getPersistenceManager();
	        	try {
	        		pm.makePersistent(si);
	        	} 
	        	catch(Exception e)
	        	{
	        		throw e;
	        	}finally 
	        	{
	        		pm.close();
	        	}
		    } else
		    {
		    	resp.getWriter().println("Some parameters are not correct.");
		    }   	
	    } catch (Exception ex) {
	    	resp.getWriter().println("Exception." + ex.toString());
	    }
	}
}
